﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WordNet.Core;
using System.ComponentModel.Composition;
using System.Configuration;
using WordNet.Core.DataContract;
using WordNet.Core.ElementContracts;

namespace DataFileProvider
{
    [Export(typeof(IDataContext))]
    [PartCreationPolicy(CreationPolicy.NonShared)]
    public class DataFileContext:DataContext, IDataContext
    {
        private const string DICTIONARY_PATH_KEY = "dicPath";
        static readonly string _dictionaryPath = ConfigurationManager.AppSettings[DICTIONARY_PATH_KEY]; 
       
        Uri _uri;
        Dictionary<Type, object> _cache;
        public DataFileContext(Uri uri)
        {
            _uri = uri;
            _cache = new Dictionary<Type, object>();
        }
        public DataFileContext()
            : this(new Uri(_dictionaryPath))
        { }
        
        public override IDataProvider<T> GetDataProvider<T>()
        {
            Type t = typeof(T);
            return ((IDataMapper<T>)_cache[t]).DataProvider;
        }
        
        protected override IDataMapper<T> GetDataMapper<T>()
        {
            Type t = typeof(T);
            if (!_cache.ContainsKey(t))
            {
                if (t == typeof(IIndexWord))
                {
                    _cache.Add(t, new IndexWordMapper(new FileProvider<IIndexWord>(_uri)));
                }
                else if (t == typeof(ISynset))
                {
                    _cache.Add(t, new SynsetMapper(new FileProvider<ISynset>(_uri)));
                }
                else if (t == typeof(ISenseEntry))
                {
                    _cache.Add(t, new SenseEntryMapper(new FileProvider<ISenseEntry>(_uri)));
                }
                else if (t == typeof(IExceptionEntry))
                {
                    _cache.Add(t, new ExceptionEntryMapper(new FileProvider<IExceptionEntryProxy>(_uri)));
                }
            }
            return (IDataMapper<T>)_cache[t]; 
        }
    }
}
